import {addUserGps,getClockInInfo} from '@/api/configure.js';
import {getLocation, getSystemInfo, getUserInfo, timesFormat} from '@/util/util.js';

export class UploadGps {
	constructor() {
		this.userGpsList = [];
		this.timer = null;
	}

	async getLocation() {
		let sys = await getSystemInfo();
		let loc = await getLocation();

		let userInfo = getUserInfo();


		let createTime = new Date().getTime();

		let userGps = {
			createTime: timesFormat(createTime),
			gpsStatus: (loc.latitude) ? 'GPS在状态正常' : 'GPS在状态异常',
			lat: loc.latitude,
			lng: loc.longitude,
			manufacturer: sys.brand,
			model: sys.model,
			satellites: '36',
			userId: userInfo['userId'],
			uuid: sys.deviceId,
			version: sys.version
		}

		this.userGpsList.push(userGps);
	}

	async uploadLocation() {
		let params = {};

		params.userGpsList = JSON.stringify(this.userGpsList);

		let res = await addUserGps(params);
	}

	async cycle() {
		if(this.timer) {
			clearTimeout(this.timer);
		}

		await this.getLocation();

		if(this.userGpsList.length >= 8){
			await this.uploadLocation();

			this.userGpsList = [];
		}


		this.timer = setTimeout(this.cycle.bind(this), 15000);
	}

	async pause() {
		if(this.timer) {
			clearTimeout(this.timer);
			this.timer = null;
		}
	}

	async getClockInInfo() {
		return await new Promise( async(resolve, reject) => {
			let userInfo = getUserInfo();

			if(!userInfo || userInfo['role']['roleKey'] != 'xjy'){
				reject();
				return
			}

			let createTime = new Date().getTime();

			let params = {
				createTime: timesFormat(createTime, 'yyyy-MM-dd')
			}

			let {data} = await getClockInInfo(params);

			let isCheckIn = data.find(item => item.clockType == '1');
			let isCheckOut = data.find(item => item.clockType == '2');

			(isCheckIn && !isCheckOut) ? resolve() : reject();
		})
	}
}
